<template>
  <div class="assessment">
    <h1 class="page-title">能力评估</h1>
    
    <!-- 学科选择 -->
    <div class="subject-selection">
      <el-select v-model="selectedSubject" placeholder="选择学科" @change="fetchAssessmentData">
        <el-option
          v-for="subject in subjects"
          :key="subject.id"
          :label="subject.name"
          :value="subject.name">
        </el-option>
      </el-select>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else>
      <!-- 能力雷达图 - 总是渲染卡片，但内容根据条件显示 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>能力维度评估</span>
          </div>
        </template>
        <div v-if="abilities && abilities.length > 0" id="radar-chart" style="height: 400px;"></div>
        <div v-else class="empty-chart">
          <el-empty description="暂无能力维度数据" />
        </div>
      </el-card>
      
      <!-- 能力详细分析 -->
      <el-card class="analysis-card">
        <template #header>
          <div class="card-header">
            <span>详细分析</span>
          </div>
        </template>
        <div class="ability-analysis" v-if="abilities.length > 0">
          <div v-for="(ability, index) in abilities" :key="index" class="ability-item">
            <div class="ability-header">
              <h3>{{ ability.name }}</h3>
              <div class="ability-score">
                <el-progress 
                  :percentage="ability.score" 
                  :color="getScoreColor(ability.score)"
                  :format="format => `${ability.score}分`"
                  :stroke-width="16">
                </el-progress>
              </div>
            </div>
            <div class="ability-description">{{ ability.description }}</div>
            <div class="ability-suggestions">
              <h4>提升建议</h4>
              <ul>
                <li v-for="(suggestion, idx) in ability.suggestions" :key="idx">{{ suggestion }}</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="empty-data" v-else>
          <el-empty description="暂无详细分析数据" />
        </div>
      </el-card>
      
      <!-- 学习建议 -->
      <el-card class="suggestion-card">
        <template #header>
          <div class="card-header">
            <span>学习建议</span>
          </div>
        </template>
        <div class="learning-suggestions">
          <div class="suggestion-content" v-if="learningSuggestions" v-html="learningSuggestions"></div>
          <el-empty v-else description="暂无学习建议" />
          <div class="action-buttons">
            <el-button type="primary" @click="goToPractice">开始练习</el-button>
            <el-button @click="goToAiAssistant">咨询AI助手</el-button>
          </div>
        </div>
      </el-card>
      
      <!-- 历史进步趋势 -->
      <el-card class="trend-card" v-if="progressData && progressData.length > 0">
        <template #header>
          <div class="card-header">
            <span>进步趋势</span>
          </div>
        </template>
        <div id="trend-chart" style="height: 350px;"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();
const loading = ref(true);
const selectedSubject = ref('');
const abilities = ref([]);
const learningSuggestions = ref('');
const progressData = ref([]);

// 学科列表
const subjects = ref([
  { id: 1, name: '语文' },
  { id: 2, name: '数学' },
  { id: 3, name: '英语' },
  { id: 4, name: '物理' },
  { id: 5, name: '化学' },
  { id: 6, name: '生物' },
]);

// 获取分数对应的颜色
const getScoreColor = (score) => {
  if (score < 60) {
    return '#f56c6c'; // 红色
  } else if (score < 75) {
    return '#e6a23c'; // 橙色
  } else if (score < 90) {
    return '#409eff'; // 蓝色
  } else {
    return '#67c23a'; // 绿色
  }
};

// 获取能力评估数据
const fetchAssessmentData = async () => {
  if (!selectedSubject.value) return;
  
  loading.value = true;
  
  try {
    const response = await axios.get(`/api/student/ability-assessment`, {
      params: {
        subject: selectedSubject.value
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data) {
      console.log('API返回数据:', response.data);
      
      // 检查abilities数据格式，确保是数组
      if (response.data.abilities && Array.isArray(response.data.abilities)) {
        abilities.value = response.data.abilities;
      } else {
        console.warn('API返回的abilities不是数组格式，尝试转换');
        abilities.value = [];
        
        // 尝试从返回的数据中提取能力维度
        try {
          if (response.data.knowledge_dimension !== undefined) {
            abilities.value.push({
              name: '知识维度',
              score: parseFloat(response.data.knowledge_dimension) * 10, // 确保是数字并放大10倍
              description: '对基础概念和理论的理解程度',
              suggestions: ['系统复习基础知识点', '建立知识体系，加深理解']
            });
          }
          
          if (response.data.application_dimension !== undefined) {
            abilities.value.push({
              name: '应用维度',
              score: parseFloat(response.data.application_dimension) * 10,
              description: '将知识应用到实际问题的能力',
              suggestions: ['多做应用题，训练解题思路', '尝试将所学知识应用到日常生活中']
            });
          }
          
          if (response.data.innovation_dimension !== undefined) {
            abilities.value.push({
              name: '创新维度',
              score: parseFloat(response.data.innovation_dimension) * 10,
              description: '创新思维和解决问题的独特性',
              suggestions: ['尝试用不同方法解决同一问题', '多思考开放性问题']
            });
          }
        } catch (e) {
          console.error('转换能力维度数据失败:', e);
          ElMessage.warning('数据格式异常，部分功能可能无法正常显示');
        }
      }
      
      console.log('处理后的能力维度数据:', abilities.value);
      learningSuggestions.value = response.data.suggestions || response.data.recommendation || '';
      progressData.value = response.data.progressData || [];
      
      // 先完成DOM更新，确保图表元素存在
      loading.value = false;
      
      // 添加全局标志，便于调试
      window.renderReady = false;
      
      // 使用双重nextTick确保DOM已更新完成
      nextTick(() => {
        console.log('DOM第一次更新完成');
        
        // 设置一个定时器，确保DOM真正渲染完成
        setTimeout(() => {
          console.log('延迟200ms后开始渲染图表');
          window.renderReady = true;
          
          // 确保雷达图容器存在
          const radarChart = document.getElementById('radar-chart');
          console.log('渲染前检查雷达图DOM:', radarChart);
          
          renderRadarChart();
          renderTrendChart();
        }, 200);
      });
    }
  } catch (error) {
    console.error('获取能力评估数据失败:', error);
    ElMessage.error('获取能力评估数据失败，请稍后重试');
    loading.value = false;
  }
};

// 渲染雷达图
const renderRadarChart = () => {
  // 基础检查
  if (!abilities.value || abilities.value.length === 0) {
    console.log('没有能力数据，不渲染雷达图');
    return;
  }
  
  // 确保DOM已经准备好
  nextTick(() => {
    let chartDom = document.getElementById('radar-chart');
    console.log('雷达图DOM元素:', chartDom);
    
    // 如果DOM元素不存在
    if (!chartDom) {
      console.warn('雷达图容器不存在，尝试重新获取或创建');
      
      // 先尝试再次获取
      const chartCard = document.querySelector('.chart-card');
      
      if (!chartCard) {
        console.error('无法找到.chart-card元素');
        return;
      }
      
      // 检查是否有v-if条件使.chart-card隐藏了radar-chart
      const radarContainer = chartCard.querySelector('#radar-chart');
      
      // 如果找不到，尝试创建一个
      if (!radarContainer) {
        console.log('创建雷达图容器元素');
        const newContainer = document.createElement('div');
        newContainer.id = 'radar-chart';
        newContainer.style.height = '400px';
        
        // 添加到卡片内容区
        const cardContent = chartCard.querySelector('.el-card__body');
        if (cardContent) {
          // 清除任何现有内容
          while (cardContent.firstChild) {
            cardContent.removeChild(cardContent.firstChild);
          }
          
          // 添加图表容器
          cardContent.appendChild(newContainer);
          chartDom = newContainer; // 更新chartDom引用
        } else {
          console.error('无法找到卡片内容区域');
          return;
        }
      } else {
        chartDom = radarContainer; // 更新chartDom引用
      }
    }
    
    try {
      // 创建echarts实例
      const myChart = echarts.init(chartDom);
      console.log('echarts实例化完成');
      
      // 准备雷达图指标和数据
      const indicators = abilities.value.map(ability => ({
        name: ability.name || '未命名能力',
        max: 100
      }));
      console.log('雷达图指标:', indicators);
      
      const data = abilities.value.map(ability => {
        const score = parseFloat(ability.score);
        return isNaN(score) ? 0 : score;
      });
      console.log('雷达图数据:', data);
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        radar: {
          indicator: indicators,
          radius: '65%'
        },
        series: [
          {
            type: 'radar',
            data: [
              {
                value: data,
                name: '能力评分',
                areaStyle: {
                  color: 'rgba(26, 115, 232, 0.3)'
                },
                lineStyle: {
                  color: '#1a73e8'
                },
                itemStyle: {
                  color: '#1a73e8'
                }
              }
            ]
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        myChart.resize();
      });
      
      console.log('雷达图渲染完成');
    } catch (error) {
      console.error('渲染雷达图出错:', error);
    }
  });
};

// 渲染趋势图
const renderTrendChart = () => {
  const chartDom = document.getElementById('trend-chart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  
  // 如果没有进度数据，显示暂无数据的提示
  if (!progressData.value || progressData.value.length === 0) {
    myChart.setOption({
      title: {
        text: '暂无历史进步数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'bottom',
        style: {
          text: '继续练习和测试后将显示您的进步趋势',
          fill: '#999',
          fontSize: 14
        }
      }
    });
    return;
  }
  
  // 准备趋势图数据
  const dates = progressData.value.map(item => item.date);
  const scores = progressData.value.map(item => item.score);
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      name: '分数'
    },
    series: [
      {
        data: scores,
        type: 'line',
        smooth: true,
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#1a73e8'
        },
        itemStyle: {
          color: '#1a73e8'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(26, 115, 232, 0.5)'
            },
            {
              offset: 1,
              color: 'rgba(26, 115, 232, 0.05)'
            }
          ])
        }
      }
    ]
  };
  
  myChart.setOption(option);
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 导航到练习页面
const goToPractice = () => {
  router.push({
    path: '/student/practice',
    query: { subject: selectedSubject.value }
  });
};

// 导航到AI助手页面
const goToAiAssistant = () => {
  router.push({
    path: '/student/assistant',
    query: { subject: selectedSubject.value }
  });
};

onMounted(() => {
  // 默认选择第一个学科
  if (subjects.value.length > 0) {
    selectedSubject.value = subjects.value[0].name;
    fetchAssessmentData();
  }
});
</script>

<style scoped>
.assessment {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.subject-selection {
  margin-bottom: 20px;
}

.loading-container {
  margin: 40px 0;
}

.chart-card,
.analysis-card,
.suggestion-card,
.trend-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ability-analysis {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 20px;
}

.ability-item {
  padding: 15px;
  border-radius: 6px;
  background-color: #f8f9fa;
}

.ability-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.ability-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.ability-score {
  width: 180px;
}

.ability-description {
  margin-bottom: 15px;
  color: #606266;
  line-height: 1.5;
}

.ability-suggestions h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 15px;
  color: #303133;
}

.ability-suggestions ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
}

.ability-suggestions li {
  margin-bottom: 5px;
}

.learning-suggestions {
  margin-bottom: 20px;
}

.empty-data {
  padding: 30px 0;
  text-align: center;
}

.suggestion-content {
  margin-bottom: 20px;
  line-height: 1.6;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .ability-analysis {
    grid-template-columns: 1fr;
  }
  
  .ability-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .ability-score {
    width: 100%;
    margin-top: 10px;
  }
}
</style> 